/*
 * AddProductToCart.java
 *
 * Created on April 5, 2007, 4:57 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.actions;

import Data.*;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.*;

/**
 *
 * @author Danny Beutler
 */
public class AddProductToCart implements edu.byu.isys413.web.Action{
    
    /** Creates a new instance of AddProductToCart */
    public AddProductToCart() {
    }
    
    public String process(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        
        //Create a sale RevenueSource
        SaleDAO saleDAO = (SaleDAO) RevenueSourceFactory.getInstance().getDAO("googleintex.SaleBO");
        SaleBO sale = saleDAO.create();
        //Attach the Product to the sale
        ConceptualProductBO conceptualProduct = (ConceptualProductBO) ConceptualProductDAO.getInstance().read(request.getParameter("id"));
        sale.setProduct(conceptualProduct);
        int quantity=0;
        try {
            //Attach the Quantity to the sale
            quantity = Integer.valueOf(request.getParameter("quantity"));
        } catch (NumberFormatException ex) {
            request.setAttribute("parameterNames","Please enter a valid quantity!");
            return "buyStuff.jsp";
        }
        if(quantity<1){
            request.setAttribute("parameterNames","Please enter a quantity greater than 1");
            return "buyStuff.jsp";
        }
        sale.setQuantity(quantity);
        //Calculate Price
        sale.calculatePrice();
        //Add the Description
        sale.setDescription(conceptualProduct.getDescription());
        //Add the RevenueSource to a TransactionLine
        TransactionLineBO transLine = TransactionLineDAO.getInstance().create();
        transLine.setRevenueSource(sale);
        //Put the transactionLine in the Session
        session.setAttribute(transLine.getId(),transLine);
        //Add the transaction to the transactionLine
        TransactionBO transaction = (TransactionBO) session.getAttribute("transaction");
        transLine.setTransaction(transaction);
        //Add the Transactionline to the Transaction in the session
        transaction.addTxLine(transLine);
        
        return "buyStuff.jsp";
    }
}
